package com.xingfly.service;

import com.xingfly.exception.TipException;
import com.xingfly.model.Interest;
import com.xingfly.model.Tag;
import com.xingfly.repository.InterestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户关注标签服务
 * Created by SuperS on 2016/12/12.
 */
@Service
public class InterestService {
    @Autowired
    private InterestRepository interestRepository;

    @Autowired
    private AccountService accountService;
    @Autowired
    private TagService tagService;

    /**
     * 创建关注
     *
     * @param userId 用户ID
     * @param tagId  标签ID
     */
    public Interest create(Long userId, Long tagId) {
        if (userId == null || tagId == null) {
            throw new TipException("用户ID和TagID不能为空");
        }
        Interest interest = new Interest();
        interest.setTag(tagService.findTagById(tagId));
        interest.setUser(accountService.find(userId));
        return interestRepository.save(interest);
    }

    /**
     * 撤销关注
     *
     * @param userId 用户ID
     * @param tagId  标签ID
     */
    public void delete(Long userId, Long tagId) {
        interestRepository.deleteByUserIdAndTagId(userId, tagId);
    }

    /**
     * 获取关注某标签的用户id列表
     *
     * @param tagId 标签ID
     */
    public List<Long> getUsersIdByTagId(Long tagId) {
        return interestRepository.findUsersIdByTagId(tagId);
    }

    /**
     * 判断某个用户是否已经关注某个tag
     *
     * @param userId 用户ID
     * @param tagId  标签ID
     */
    public boolean isInterestInTag(Long userId, Long tagId) {
        return interestRepository.findByUserIdAndTagId(userId, tagId) != null;
    }

    /**
     * 获取用户关注的Tag列表
     *
     * @param userId 用户ID
     */
    public List<Tag> getTagsByUserId(Long userId) {
        return interestRepository.findTagsByUserId(userId);
    }

    /**
     * 判断用户对列表中的Tag是否已经关注
     *
     * @param userId 用户ID
     * @param tags   tag列表
     */
    public Map<Long, Boolean> hasInterestInTags(Long userId, List<Tag> tags) {
        Map<Long, Boolean> map = new HashMap<>();
        if (CollectionUtils.isEmpty(tags) || userId == null) {
            throw new TipException("用户ID和Tag列表不能为空");
        }
        for (Tag tag : tags) {
            map.put(tag.getId(), isInterestInTag(userId, tag.getId()));
        }
        return map;
    }
}
